<!-- 在这个文件对每个tab对应的列表进行渲染 -->
<template>
	<view class="item-container">
		<!-- 这里设置了z-paging加载时禁止自动调用reload方法，自行控制何时reload（懒加载）-->
		<!--  :enable-back-to-top="currentIndex===tabIndex" 在微信小程序上可以多加这一句，因为默认是允许点击返回顶部的，但是这个页面有多个scroll-view，会全部返回顶部，所以需要控制是当前index才允许点击返回顶部 -->
		<z-paging ref="paging" v-model="dataList" @query="queryList" @scroll="pageScrollFn" :hide-no-more-inside="true" :fixed="false" :auto="true">
			<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
			<template #refresher="{refresherStatus}" style="height: 200rpx;">
						<!-- 此处的custom-refresh为demo中自定义的组件，非z-paging的内置组件，请在实际项目中自行创建。这里插入什么view，下拉刷新就显示什么view -->
				<image src="/static/home/refreshLoading.gif" mode="heightFix" style="height: 100rpx;margin: 0 auto;display: block;"></image>
				<view class="u-text-center">{{statusTextArr[refresherStatus]}}</view>
			</template>
			<!-- 自定义没有更多数据view -->
			<template #loadingMoreNoMore>
				<view class="u-flex u-col-center u-row-center">
					<u-line color="#DFDFDF" length="110rpx"/>
					<view class="u-flex u-m-l-30 u-m-r-30" style="flex-direction: column;align-items: center;">
						<image src="/static/home/noMore.png" mode="heightFix" style="height:50rpx;margin: 0 auto;display: block;"></image>
						<text class="u-font-10 u-m-t-6" style="color:#999">没有更多了</text>
					</view>
					<u-line color="#DFDFDF" length="110rpx"/>
				</view>
				
			</template>
			<view class="item-content">
				<view class="u-flex u-row-between u-m-t-20 u-m-b-30">
					<text>只显示可购买</text>
					<u-switch v-model="isShowBuy" size="40" active-color="#ffbb1a" inactive-color="#ccc" @change="loadAgainFn"></u-switch>
				</view>
				<view class="item-list u-m-b-20  u-flex" v-for="(item,index) in dataList" :key="index" @click="itemClick(item)">
					<image :src="item.url" mode="" class="item-image u-m-r-24"></image>
					<view class="item-info">
						<view class="u-flex u-row-between" style="flex-direction: column;" >
							<view style="width: 100%;">
								<view class="u-flex u-col-top" @click.stop>
									<view class="item-name u-line-2" @click="itemClick(item)" style="flex:1;">{{item.itemName}}</view>
									<u-icon name="star" v-if="!item.isCollect" @click="addCollectFn(item.id)" color="#999" size="50" class="u-m-l-20"></u-icon>
									<u-icon name="star-fill" v-else color="#FF831A" @click="removeCollectFn(item.id,item.groupId)" size="50" class="u-m-l-20"></u-icon>
								</view>
								<view class="item-val  u-m-t-14 u-m-b-6" style="border: 1px solid #FF551A;">
									<view class="item-val-text item-val-specifica-title">规格</view>
									<view class="item-val-text item-val-specifica-text">{{item.specification}}</view>
								</view>
								<br /> 
								<view class="item-val" style="border: 1px solid #C09A87;">
									<view class="item-val-text item-val-owner-title">品牌商</view>
									<view class="item-val-text item-val-owner-text">{{item.brandOwnerName}}</view>
								</view>
							</view>
							<view class="u-flex u-row-between u-col-bottom " style="width: 100%;">
								<view class="u-flex u-col-bottom">
									<view class="item-price u-font-32 u-m-r-20">￥{{item.price}}</view>
									<view class="item-stock u-font-24">{{item.inventoryStatus}}</view>
								</view>
								<view :class="['item-add', 'u-flex', 'u-row-center',{'item-no-add':!item.isPurchasable}]"  @click.stop="addItemFn(item)" >
								<!-- v-if="item.isPurchasable&&(item.inventoryBalance>=item.sellingUnit)" -->
									<view class="u-font-22">加购</view>
									<u-icon name="plus" color="#C88D00" size="18"></u-icon>
								</view>
							</view>
						</view>
					</view>
					<!-- <image src="/static/xiaoshou/noSign.png" mode="" class="no-sign" v-if="!item.isPurchasable"></image> -->
				</view>
			</view>
			
		</z-paging>
		<u-mask :show="showChoseNum" :z-index="888" :custom-style="{background: 'rgba(0, 0, 0, 0.3)'}" @click="showChoseNum = false"></u-mask>
		<view v-if="showChoseNum" class="chose-num box-padding">
			<view class="u-flex u-row-between" style="height: 111rpx; padding-bottom: 20rpx;">
				<text class="text-bold">下单数量</text>
				<number-box box-width="100rpx" width="200rpx" height="50rpx" fontSize="28rpx"
				 :value="quantity"
				  :step="product.sellingUnit?product.sellingUnit:1" 
				  :min="product.sellingUnit?product.sellingUnit:1" 
				  :max="product.inventoryBalance" 
				  @change="updateQuantity"></number-box>
			</view>
			<view class=" u-m-b-30 sellunit-box">
				最小销售单位 {{product.sellingUnit}}  {{product.unit||'瓶'}}
			</view>
			<u-button shape="circle" hover-class="none" :ripple="true" :hair-line="false" :custom-style="getBtStyle('default')" @click.native="AddCartFn">加入购物车</u-button>
		</view>
		<view :class="['shop-cart-container',transformClass?'shop-cart-active':'']" @click="goShopCartFn">
			<u-icon name="shopping-cart" style="font-size: 60rpx;font-weight: bold;"></u-icon>
		</view>
		<u-action-sheet  v-model="chooseGroupShow" :list="groupShowList" :labelName="'name'" @click="addItemGroupFn" safe-area-inset-bottom	></u-action-sheet>
	</view>
</template>

<script>
	import NumberBox from '@/components/number-box/index.vue';
	import { useUserStore } from '@/store/user.js';
	import { useShopStore } from '@/store/shop.js';
	import { mapState } from 'pinia';
	export default {
		components:{ NumberBox },
		data() {
			return {
				//v-model绑定的这个变量不要在分页请求结束中自己赋值！！！
				dataList: [],
				isShowBuy:true,
				showChoseNum:false,
				product:{},
				quantity:1,
				timer:null,
				transformClass:true,
				statusTextArr: ['哎呀，用点力继续下拉！', '拉疼我啦，松手刷新~~', '正在努力刷新中...', '刷新成功啦~'],
				groupShowList:[],
				chooseGroupShow:false,
				addGroupItemId:'',
			}
		},
		props:{
			SellerId:{
				type:String,
				default:""
			},
			keyWords:{
				type:String,
				default:""
			},
			searchBrand: {
				type: Array,
				default () {
					return []
				}
			},
			searchClass: {
				type: Array,
				default () {
					return []
				}
			},
			searchOwner: {
				type: Array,
				default () {
					return []
				}
			},
			startPrice:{
				type:String,
				default:""
			},
			endPrice:{
				type:String,
				default:""
			},
			SortBy:{
				type:Number,
				default:0
			}
		
		},
		created(){
			// this.$refs.paging.reload();
		},
		computed:{
			...mapState(useUserStore,['isPurchase']),
			...mapState(useShopStore, {storeShop: 'shop'})
		},
		methods: {
			 addCollectFn(id){
				if(this.groupShowList.length == 0){
					 this.getGroupList()
				};
				console.log(id);
				this.addGroupItemId = id;
				this.chooseGroupShow = true;
			},
			async removeCollectFn(id,groupId){
				uni.showLoading({
					title:'loading...'
				})
				let params = {
					ItemIds: [id],
					groupId:groupId,
				}
				if (groupId === 'default-group'||!groupId) {
					delete params.groupId
				}
				const res = await this.$newHttp.delete('api/v1.2/Favorite/Remove'+this.$u.queryParams(params, true, 'repeat'));
				uni.hideLoading();
				if(res.code === 200){
					uni.showToast({
						title:'删除成功'
					});
					this.$refs.paging.refresh();
				}else{
					this.$u.toast('删除失败,错误信息：'+res.erroMessage, 2000);
				}
			},
			async addItemGroupFn(val){
				uni.showLoading({
					title:'loading...'
				})
				let params = {
					itemId: this.addGroupItemId,
					sellerId: this.SellerId,
					groupId:this.groupShowList[val].id
				}
				if (this.groupShowList[val].id === 'default-group') {
					delete params.groupId
				}
				const res = await this.$newHttp.post('api/v1.2/Favorite/Add', params);
				uni.hideLoading();
				if (res.code === 200) {
					this.$u.toast('添加收藏成功', 1000, 'success');
					this.$refs.paging.refresh()
				}else{
					this.$u.toast('添加收藏失败,错误信息：'+res.erroMessage, 2000);
				}
			},
			async getGroupList(){
				const res = await this.$newHttp.get('api/v1.2/Favorite/GetAllGroups');
				if(res.code === 200){
					let ary = [{
						name:'默认',
						id:"default-group"
					}];
					if(res.data.length!=0){
						ary.push(...res.data);
					}
					this.groupShowList = ary;
					console.log(this.groupShowList);
				}
			},
			// 滚动隐藏购物车
			pageScrollFn(){
				this.transformClass = true; //要添加的class类名
				clearTimeout(this.timer);//这里必须要每次滚动前 清除一次
				// 如果停留则表示滚动结束  一旦空了1s就判定为滚动结束
				this.timer = setTimeout(() => {
				  this.transformClass = false //滚动结束清除class类名
				}, 1500);
			},
			async AddCartFn(){
				let params = {
					itemId: this.product.id,
					sellerShopId: this.SellerId,
					quantity: this.quantity,
					buyerShopId: this.storeShop.id,
				}
				uni.showLoading({
					title:'loading...'
				})
				const res = await this.$newHttp.post('api/ShoppingCart/AddShoppingCart', params);
				uni.hideLoading();
				if (res.code === 200) {
					this.$u.toast('添加成功', 1000, 'success');
					this.showChoseNum = false;
				}else{
					this.showChoseNum = false;
					this.$u.toast('加入购物车失败，错误信息：'+res.erroMessage);
				}
			},
			loadAgainFn(){
				if(Number(this.startPrice)>Number(this.endPrice)){
					this.$u.toast('价格区间筛选格式不正确，请输入正确的价格区间~');
					return false; 
				}
				this.$refs.paging.reload(); 
			},
			goShopCartFn(){
				if(!this.transformClass){
					if (!this.isPurchase) {
						return this.$u.toast('当前账号没有查看购物车的权限，请联系管理员处理~');
					}else{
						uni.navigateTo({
							url: '/pages/sale/homePage/shopCart',
						});
					};
				};
				this.transformClass = false;
			},
			addItemFn(item){
				// item.isPurchasable&&(item.inventoryBalance>=item.sellingUnit)
				if(!this.isPurchase){
					return this.$u.toast('当前账号没有下单的权限，请联系管理员处理~');
				}
				if(!item.isPurchasable){
					return this.$u.toast('您还没有与销售商签约此产品，请联系销售商签约~');
				}
				if(item.inventoryBalance<item.sellingUnit){
					return this.$u.toast('当前商品库存不足~');
				}
				this.quantity = item.sellingUnit;
				this.product = item;
				this.showChoseNum = true;
			},
			// 修改数量
			updateQuantity(value) {
				this.quantity = value
			},
			async queryList(pageNo, pageSize) {
				//组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				//模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageIndex: pageNo,
					pageSize: pageSize,
					BuyerId:this.storeShop.id,
					SellerId:this.SellerId,
					Purchasable:this.isShowBuy,
					KeyWords:this.keyWords,
					SortBy:this.SortBy
				}  
				if (this.searchBrand.length !== 0) {
					params.BrandFilter = this.searchBrand;
				}
				if (this.searchClass.length !== 0) {
					params.ShopCategoryFilter = this.searchClass;
				}
				if (this.searchOwner.length !== 0) {
					params.brandOwnerIds = this.searchOwner;
				}
				// this.startPrice = Number(this.startPrice);
				// this.endPrice = Number(this.endPrice);
				if (this.startPrice !=0 &&this.startPrice != '') {
					if(this.startPrice<this.endPrice){
						params.startPrice = this.startPrice;
					}
				}
				if (this.endPrice != 0 &&this.endPrice != '') {
					if(this.startPrice<this.endPrice){
						params.endPrice = this.endPrice;
					}
				}
				uni.showLoading({
					title: 'loading...',
					mask: false
				});
				const res = await this.$newHttp.get('api/v1.2/ShanNiang/GetSellerGoodsPage?'+this.$mHelper.stringify(params));
				uni.hideLoading({
					title: 'loading...'
				})
				if(res.code === 200){
					this.$refs.paging.complete(res.data.list);
				}else{
					this.$refs.paging.complete(false);
				}
			},
			itemClick(item) {
				let auth = item.isPurchasable?1:0;
				this.$mRouter.push({
					route: '/pages/index/xiangqing?id=' + item.id + '&sellerShopId=' + item.sellerShopId + '&auth=' +auth
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
	.item-container {
		height: 100%;
		.item-content{
			box-sizing: border-box;
			padding: 0 34rpx;
			.item-list{
				background-color: #fff;
				border-radius: 20rpx;
				position: relative;
				.no-sign{
					width: 130rpx;
					height: 130rpx;
					position: absolute;
					top: 0;
					right: 0;
				}
				.item-image{
					width: 230rpx;
					height: 230rpx;
					border: 1px solid #E4E4E4;
					border-radius: 10rpx;
				}
				.item-info{
					flex:1;
					.item-name{
						font-weight: 500;
						font-size: 28rpx;
					}
					.item-val{
						display: inline-block;
						font-size: 20rpx;
						box-sizing: border-box;
						border-radius: 4px;
						
						.item-val-text{
							display: inline-block;
							box-sizing: border-box;
							padding: 4rpx 10rpx;
						}
						.item-val-specifica-title{
							border-right: 1px solid #ff551a;
							background-color: #FFE1D6;
							color: #FF551A;
							border-top-left-radius: 4px;
							border-bottom-left-radius: 4px;
						}
						.item-val-specifica-text{
							color: #FF551A;
						}
						.item-val-owner-title{
							border-right: 1px solid #C09A87;
							background-color: #FAF1DF;
							color: #B88D77;
							border-top-left-radius: 4px;
							border-bottom-left-radius: 4px;
						}
						.item-val-owner-text{
							color: #B88D77;
						}
					}
					.item-price{
						font-weight: bold;
						color: #ff551a;
					}
					.item-stock{
						color: #999;
					}
					.item-add{
						background-color: #FFEEC7;
						border-radius: 24px;
						box-sizing: border-box;
						padding:10rpx 20rpx;
						border: 1px solid #C88D00;
						color: #C88D00;
						font-size: 28rpx;
					}
					.item-no-add{
						color: #9D9D9D;
						background: #E7E7E7;
						border: 1px solid #9D9D9D;
					}
				}
			}
		}
		
		.chose-num {
			// height: 250rpx;
			width: 100%;
			position: fixed;
			bottom: 0;
			background-color: #FFFFFF;
			z-index: 999;
			box-sizing: border-box;
			padding-bottom: 20rpx;
			/* #ifdef APP-PLUS */
			padding-bottom: env(safe-area-inset-bottom);
			/* #endif */
			.sellunit-box{
				background-color: #f8f8f8;
				color:#999;
				box-sizing: border-box;
				padding: 20rpx 30rpx;
			}
		}
		.shop-cart-container{
			position: fixed;
			bottom: 200rpx;  
			right: 14rpx; 
			z-index: 887;
			width: 120rpx; 
			height: 120rpx; 
			border-radius: 50%; 
			background-color: #FFBB1A;
			display: flex;
			justify-content: center;
			align-items: center;
			box-shadow: 0px 0px 18px 2px rgba(6,0,1,0.1);
			transition: all 0.5s ease;
		}
		.shop-cart-active{
			right: -60rpx;
			opacity:0.4;
			transition: all 0.5s ease;
		}
	}


</style>
